package com.zj.musicTools.page

import android.util.Log
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.zj.musicTools.R
import com.zj.musicTools.function.AppPath.Companion.appPath
import com.zj.musicTools.ui.theme.MusicToolsTheme
import java.io.File
import java.util.regex.Pattern


@Composable
fun logPage() {
    val logPath = appPath.logPath()
    val filer=File(logPath)
    var logMsg = if(filer.exists())filer.readText() else "未产生运行日志 "

//    val bufMsg = Agent.ffmpeg()

    Surface(/*color = MaterialTheme.colorScheme.primary*/) {
        Column(modifier = Modifier
            .fillMaxSize()
            .padding(bottom = 60.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally)
        {
            Row(modifier = Modifier
                .fillMaxSize()
                .padding(20.dp)
                .border(
                    1.dp,
                    color = MaterialTheme.colorScheme.primary,
                    shape = RoundedCornerShape(5.dp)
                ),
                verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center
            ) {
                Text(text = multiColorText(logMsg),
                    modifier = Modifier
                        .verticalScroll(rememberScrollState())
                        .align(Alignment.CenterVertically)
                        .padding(10.dp)

                )
//                multiColorText(logMsg)
            }
        }
    }
//    Text(text = "logPage")


}


//关键词
/*
*  result=false 全红色
*  [ - -  : : ] 绿色
*   其他         黑色
*val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // HH:mm:ss//获取当前时间
* r'\b\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\b'
* 截取[ 中间] 数据，判断
*
* */


/**
 * log拆分函数
* */
@Composable
fun String.logSplit(callback: @Composable (Int, String)->Unit){
    val bufText=this
    Log.i("logSplit()","begin")

    val format="\\[yyyy-MM-dd HH:mm:ss\\]".replace("yyyy", "\\d{4}").replace("MM", "\\d{2}").replace("dd", "\\d{2}").replace("HH", "\\d{2}").replace("mm", "\\d{2}").replace("ss", "\\d{2}")
    val mather= Pattern.compile(format).matcher(this)

    val list = mutableListOf<String>()
    var lastEndIndex = 0
    var end = 0
    while(mather.find()){
        val start = mather.start()
        end = mather.end()
        if(lastEndIndex < start){//分隔符前内容
            val strip=bufText.substring(lastEndIndex,start)
            list.add(strip)

            if(strip.contains("result=false")){
                callback(1,strip)
            }else {
                val lines = strip.splitToSequence("\n").map { it + "\n" }.toList()
                for ( line in lines ){
                    if(line.isEmpty())continue
                    var pos = line.indexOf("<Err>")
                    if (pos >= 0) {     //错误行
                        pos += "<Err>".length
                        callback(1, line.substring(pos,line.length))
                    }else{              //正常行
                        callback(0, line)
                    }
                }
            }
        }
        list.add(mather.group())
        callback(2,mather.group())
        lastEndIndex = end
    }
    val strip=bufText.substring(end,bufText.length-1)
    list.add(strip)
    if(strip.contains("result=false")){
        callback(1,strip)
    }else {
        val lines = strip.splitToSequence("\n").map { it + "\n" }.toList()
        for ( line in lines ){
//            if(line.isBlank())continue
            var pos = line.indexOf("<Err>")
            if (pos >= 0) {     //错误行
                pos += "<Err>".length
                callback(1, line.substring(pos,line.length))
            }else{              //正常行
                callback(0, line)
            }
        }
    }

//        Log.i("logSplit()","size: ${list.size} the msg: ${list}")
}


/**
 * log代码颜色拆分
 *
 * */
@Composable
fun multiColorText(logMsg:String): AnnotatedString {

    val annotatedString = buildAnnotatedString {

        logMsg.logSplit() {
            type,msg->
            when(type) {
                1 ->
                    withStyle(style = SpanStyle(color = colorResource(R.color.musicRed))) {
                    append(msg)
                    }
                2->
                    withStyle (style = SpanStyle(color = colorResource(R.color.musicGreen3))) {
                    append(msg)
                    }
                0->
                    withStyle (style = SpanStyle(color = colorResource(R.color.black))) {
                    append(msg)
                    }
            }
        }
    }
    return annotatedString
}

@Preview(showBackground = true)
@Composable
private fun DefaultPreview() {
    MusicToolsTheme {
        logPage()
    }
}